import { Config } from "../config.js";

class DeepSeek {
  name: string;
  description: string;
  api: string;
  model: string;
  headers: { [key: string]: string };

  constructor(config: Config) {
    this.name = "DeepSeek";
    this.description =
      "DeepSeek is a large language model developed by DeepSeek.";
    this.api = config.ai.deepSeekApiUrl;
    this.model = "deepseek-chat";
    this.headers = {
      "Content-Type": "application/json",
      Authorization: `Bearer ${config.ai.deepSeekApiKey}`,
    };
  }
  async chat(messages: string[], tools: any[] = []) {
    const body = {
      model: this.model,
      messages: messages,
      max_tokens: 2048,
      temperature: 0.7,
      top_p: 1.0,
      n: 1,
      tools: tools,
      tool_choice: "auto", // 自动选择工具
    };
    try {
      const response = await fetch(this.api, {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        throw new Error(
          `HTTP error! status: ${response.status}${JSON.stringify(messages)}`
        );
      }

      const data = await response.json();
      if (data.choices.length === 0) {
        throw new Error("No choices returned from DeepSeek API");
      }

      return data.choices[0].message;
    } catch (error) {
      console.error("Error in DeepSeek chat:", error);
      throw error;
    }
  }
  async completion(prompt: string) {
    const body = {
      model: this.model,
      prompt: prompt,
      max_tokens: 2048,
      temperature: 0.7,
      top_p: 1.0,
      n: 1,
    };
    try {
      const response = await fetch(this.api, {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      return data.choices[0].text;
    } catch (error) {
      console.error("Error in DeepSeek completion:", error);
      throw error;
    }
  }
  async stream(messages: string[], callback: (text: string) => void) {
    const body = {
      model: this.model,
      messages: messages,
      max_tokens: 2048,
      temperature: 0.7,
      top_p: 1.0,
      n: 1,
    };
    try {
      const response = await fetch(this.api, {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      if (!response.body) {
        throw new Error("Response body is null");
      }
      const reader = response.body.getReader();
      let done = false;
      while (!done) {
        const { value, done: doneReading } = await reader.read();
        done = doneReading;
        if (value) {
          const text = new TextDecoder().decode(value);
          callback(text);
        }
      }
    } catch (error) {
      console.error("Error in DeepSeek stream:", error);
      throw error;
    }
  }
  async embed(text: string) {
    const body = {
      model: this.model,
      input: text,
    };
    try {
      const response = await fetch(`${this.api}/embeddings`, {
        method: "POST",
        headers: this.headers,
        body: JSON.stringify(body),
      });
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      return data.data[0].embedding;
    } catch (error) {
      console.error("Error in DeepSeek embed:", error);
      throw error;
    }
  }
}

export function createDeepSeekClient(config: Config) {
  const apiKey = config.ai.deepSeekApiKey;
  if (!apiKey) {
    throw new Error("未配置DeepSeek API密钥");
  }
  return new DeepSeek(config);
}
